package utils

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"gopkg.in/oauth2.v3/utils/uuid"
	"strconv"
	"strings"
	"time"
)

const ResetPassWord  = "ResetPassWord"

func GenUniqueToken(salt string) string {
	buf := bytes.NewBufferString(salt)
	buf.WriteString(strconv.Itoa(int(time.Now().UnixNano())))
	token := base64.URLEncoding.EncodeToString(uuid.NewMD5(uuid.Must(uuid.NewRandom()), buf.Bytes()).Bytes())
	token = strings.Replace(strings.TrimRight(token, "="), "_", "-", -1)
	return token
}

func ObjectToMap(object interface{}) (map[string]interface{},error) {
	input,err := json.Marshal(object)
	if err != nil{
		return nil,err
	}

	resultMap := map[string]interface{}{}
	err = json.Unmarshal(input,&resultMap)
	if err != nil{
		return nil,err
	}

	return resultMap,nil
}

func MsToString(ms int64) string {
	tm := time.Unix(0,ms * int64(time.Millisecond))
	timeStr := tm.Format("2006-01-02 15:04:05.000")

	return timeStr
}


func CreateUpdateColumns(columns []string) string {
	length := len(columns)
	s := make([]string, 0, length)
	start := 1
	for start <= length {
		s = append(s, fmt.Sprintf("%s = $%d", columns[start-1], start))
		start++
	}
	return strings.Join(s, ",")
}
